/**
 * Copyright 2010-2016 the original author or authors.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.mybatis.spring.config;

import org.mybatis.spring.mapper.ClassPathMapperScanner;
import org.mybatis.spring.mapper.MapperFactoryBean;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.beans.factory.xml.XmlReaderContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;

import java.lang.annotation.Annotation;

/**
 * Mybatis自定义Xml定义的解析器,用于配置在Spring中Mybatis的相关数据.
 * <p>
 * A {#code BeanDefinitionParser} that handles the element scan of the MyBatis.
 * namespace
 *
 * @author Lishu Luo
 * @author Eduardo Macarron
 * @see MapperFactoryBean
 * @see ClassPathMapperScanner
 * @since 1.2.0
 */

public class MapperScannerBeanDefinitionParser implements BeanDefinitionParser {

    /**
     * 扫描基础包路径
     */
    private static final String ATTRIBUTE_BASE_PACKAGE = "base-package";
    /**
     * Mapper定义必须持有的注解定义
     */
    private static final String ATTRIBUTE_ANNOTATION = "annotation";
    /**
     * Mapper定义必须实现的父接口
     */
    private static final String ATTRIBUTE_MARKER_INTERFACE = "marker-interface";
    /**
     * 指定Mapper Bean name 的名称生成器
     */
    private static final String ATTRIBUTE_NAME_GENERATOR = "name-generator";
    /**
     * 指定SqlSessionTemplate的实例
     */
    private static final String ATTRIBUTE_TEMPLATE_REF = "template-ref";
    /**
     * 指定SqlSessionFactory的实例
     */
    private static final String ATTRIBUTE_FACTORY_REF = "factory-ref";

    /**
     * {@inheritDoc}
     */
    @Override
    public synchronized BeanDefinition parse(Element element, ParserContext parserContext) {
        // 生成类扫描注册器
        ClassPathMapperScanner scanner = new ClassPathMapperScanner(parserContext.getRegistry());
        // 获取类加载器
        ClassLoader classLoader = scanner.getResourceLoader().getClassLoader();

        XmlReaderContext readerContext = parserContext.getReaderContext();
        // 设置资源加载器
        scanner.setResourceLoader(readerContext.getResourceLoader());
        try {
            // 配置注解限制
            String annotationClassName = element.getAttribute(ATTRIBUTE_ANNOTATION);
            if (StringUtils.hasText(annotationClassName)) {
                @SuppressWarnings("unchecked")
                Class<? extends Annotation> markerInterface = (Class<? extends Annotation>) classLoader.loadClass(annotationClassName);
                scanner.setAnnotationClass(markerInterface);
            }
            // 配置父接口限制
            String markerInterfaceClassName = element.getAttribute(ATTRIBUTE_MARKER_INTERFACE);
            if (StringUtils.hasText(markerInterfaceClassName)) {
                Class<?> markerInterface = classLoader.loadClass(markerInterfaceClassName);
                scanner.setMarkerInterface(markerInterface);
            }
            // 配置名称生成器
            String nameGeneratorClassName = element.getAttribute(ATTRIBUTE_NAME_GENERATOR);
            if (StringUtils.hasText(nameGeneratorClassName)) {
                Class<?> nameGeneratorClass = classLoader.loadClass(nameGeneratorClassName);
                BeanNameGenerator nameGenerator = BeanUtils.instantiateClass(nameGeneratorClass, BeanNameGenerator.class);
                scanner.setBeanNameGenerator(nameGenerator);
            }
        } catch (Exception ex) {
            readerContext.error(ex.getMessage(), readerContext.extractSource(element), ex.getCause());
        }
        // 配置SqlSessionTemplate
        String sqlSessionTemplateBeanName = element.getAttribute(ATTRIBUTE_TEMPLATE_REF);
        scanner.setSqlSessionTemplateBeanName(sqlSessionTemplateBeanName);
        // 配置SqlSessionFactory
        String sqlSessionFactoryBeanName = element.getAttribute(ATTRIBUTE_FACTORY_REF);
        scanner.setSqlSessionFactoryBeanName(sqlSessionFactoryBeanName);
        scanner.registerFilters();
        String basePackage = element.getAttribute(ATTRIBUTE_BASE_PACKAGE);
        // 执行扫包加载Mapper定义的操作
        scanner.scan(StringUtils.tokenizeToStringArray(basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
        return null;
    }

}
